package com.example.servlet;



import com.example.dao.CustomerDao;
import com.example.entity.Customer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private CustomerDao customerDao = new CustomerDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println("尝试登录 - 用户名: " + username + ", 密码: " + password);

        Customer customer = customerDao.findByUsername(username);

        if (customer != null) {
            System.out.println("数据库中的用户信息 - 密码: " + customer.getPassword());
        } else {
            System.out.println("未找到用户");
        }

        if (customer != null && customer.getPassword().equals(password)) {
            HttpSession session = request.getSession();
            session.setAttribute("customer", customer);

            String autoLogin = request.getParameter("autoLogin");
            if ("on".equals(autoLogin)) {
                Cookie usernameCookie = new Cookie("username", username);
                Cookie passwordCookie = new Cookie("password", password);
                usernameCookie.setMaxAge(7 * 24 * 60 * 60);
                passwordCookie.setMaxAge(7 * 24 * 60 * 60);
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }

            response.sendRedirect("customer?action=list");
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
} 